package com.seeyon.apps.kkSample.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author 首志
 * @date 2023-12-01 15:13
 */
public class AESEncryptToBase64 {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    public static byte[] encryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
        kgen.init(128);
        SecretKey secretKey = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
    }

    public static String encrypt(String content, String encryptKey) throws Exception {
        byte[] encryptedBytes = encryptToBytes(content, encryptKey);
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
}
